package com.egao.common.module.system.transfer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.IdUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.entity.Field;
import com.egao.common.module.company.service.FieldService;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.entity.UserRole;
import com.egao.common.module.system.service.UserRoleService;
import com.egao.common.module.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;

/**
 * 辅导员角色数据导入
 * @author: dl
 */
@RestController
@Slf4j
public class UserDataController {

    @Value("${old.datasource.syurl}")
    private String url;

    @Value("${old.datasource.username}")
    private String userName;

    @Value("${old.datasource.password}")
    private String password;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult transfer() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        long beginTime = System.currentTimeMillis();
        TimeInterval timer = DateUtil.timer();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, userName, password);
            st = conn.createStatement();
            String sql = "SELECT  " +
                    "u.login_name username, " +
                    "u.`name`, " +
                    "o.code " +
                    "FROM sys_user u  " +
                    "LEFT JOIN sys_office o ON o.id = u.office_id " +
                    "WHERE u.del_flag = '0' " +
                    "AND u.`name` != 'admin'";

            st = conn.createStatement();
            log.info("运行：{}", sql);
            rs = st.executeQuery(sql);
            log.info("总数：{}", rs.getRow());
            int i = 0;
            while (rs.next()) {
                String username = rs.getString("username");
                String name = rs.getString("name");
                String code = rs.getString("code");

                User user = new User();
                user.setName(name);
                user.setUsername(username);
                // 管理员用户类型
                user.setUserType("1");
                user.setState(0);
                user.setCollegeCode(code);
                user.setPassword(userService.encodePsw(IdUtil.simpleUUID()));

                if (name == null) {
                    user.setDegreeScope("1");
                } else if (name.contains("研")) {
                    user.setDegreeScope("2");
                } else if (name.contains("法硕中心")) {
                    user.setDegreeScope("2");
                } else {
                    user.setDegreeScope("1");
                }

                i ++;
                log.info("用户信息：{} 数量：{} 个", name, i);
                if (userService.save(user)) {
                    UserRole userRole = new UserRole();
                    // 设置角色为辅导员
                    userRole.setRoleId(5);
                    userRole.setUserId(user.getUserId());
                    userRoleService.save(userRole);
                    log.info("插入用户信息：{} 数量：{} 个", name, i);
                }
            }

            log.info("完成时间 : {} 分", timer.intervalMinute());
            return JsonResult.ok(String.format("完成时间 : %s 分", timer.intervalMinute()));
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return JsonResult.ok();
    }

}
